package com.ego.controller;

import com.ego.pojo.Brand;
import com.ego.pojo.vo.ResultVO;
import com.ego.service.BrandService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Ares
 * @date 2020-11-20
 */
@Controller
@RequestMapping("/brand")
public class BrandController {
    @Resource
    private BrandService brandService;

    @GetMapping("/page")
    public ResponseEntity<ResultVO<Brand>> page(
            @RequestParam(value = "pageNo",required = false,defaultValue = "1")Integer pageNo,
            @RequestParam(value = "pageSize",required = false,defaultValue = "5")Integer pageSize,
            @RequestParam(value = "sortBy",required = false,defaultValue = "id")String sortBy,
            @RequestParam(value = "descending",required = false,defaultValue = "true")Boolean descending,
            @RequestParam(value = "key",required = false)String key
            ){
        ResultVO<Brand> page = brandService.page(pageNo, pageSize, sortBy, descending, key);
        if(page==null|| CollectionUtils.isEmpty(page.getItems())){
            return ResponseEntity.noContent().build();
        }
        return ResponseEntity.ok(page);
    }

    @DeleteMapping
    public ResponseEntity<Void> delete(@RequestParam("id")Long id){
        Integer rows = brandService.delete(id);
        if(rows>0){
            return ResponseEntity.ok().build();
        }
        return null;
    }

    @PostMapping
    public ResponseEntity<Void> save(Brand brand,@RequestParam("cids") Long[] cids){
        Integer rows = brandService.save(brand,cids);
        if(rows>0){
            return ResponseEntity.ok().build();
        }
        return ResponseEntity.status(HttpStatus.FAILED_DEPENDENCY).build();
    }

    @PutMapping
    public ResponseEntity<Void> update(Brand brand,@RequestParam("cids") Long[] cids){
        Integer rows = brandService.update(brand,cids);
        if(rows>0){
            return ResponseEntity.ok().build();
        }
        return ResponseEntity.status(HttpStatus.FAILED_DEPENDENCY).build();
    }

    @GetMapping("/cid/{cid}")
    public ResponseEntity<List<Brand>> getBrandsByCid(@PathVariable Long cid){
        return ResponseEntity.ok(brandService.selectBrandsByCid(cid));
    }

    @GetMapping("/list/ids")
    public ResponseEntity<List<Brand>> selectByIds(@RequestParam("ids") List<Long> idList){
        List<Brand> brands = brandService.selectByIds(idList);
        return ResponseEntity.ok(brands);
    }
}
